package cn.usian.interceptors;


import cn.usian.jyzx.model.entity.user.UserInfo;
import cn.usian.jyzx.model.vo.common.Result;
import cn.usian.jyzx.model.vo.common.ResultCodeEnum;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import cn.util.AuthThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptro implements HandlerInterceptor {
    @Autowired
    RedisTemplate<String,String> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //先拦截所有请求
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        //判断这个请求是否包含指定参数
        if (antPathMatcher.match("/api/**/auth/**",uri)){
            //如果包含就拦截进行判断
            String token = request.getHeader("token");
            //获取报文中的token数据并在redis中获取
            String tokenRedis = redisTemplate.boundValueOps(token).get();
            UserInfo userInfo = JSON.parseObject(tokenRedis, UserInfo.class);
            //如果登录就放行
            if (userInfo!=null){
                AuthThreadLocalUtils.set(userInfo);
                return true;
            }
            //如果没登陆就返回给前端
            Result build = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
            response.getWriter().write(JSON.toJSONString(build));
            return false;
            //如果不包含就放行
        }else {
            return true;
        }


    }
}
